<template lang="pug">
  div.table-empty
    s-table(
    ref="table"
    :reqUrl="reqUrl"
    reqMethod="GET"
    :column="tableObj.column"
    v-if="$route.path === '/finance/charge/plan/account/admin'"
    :filterProps="{ fields: searchField }"
    :queryPropsParams="{planId: id, cancelled: false }"
    )
      .table-operator(slot="table-operator")
        el-button(size="large" round @click="notifyPlanHandle()") 批量通知
        <!--el-button(size="large" round @click="printHandle()") 批量打印-->
        el-button.gradientVertical(size="large" round @click="($router.push({ path: '/finance/charge/plan/account/admin/info', query: { id: id } }))") 添加账单
      template(slot="action" slot-scope="text, scope")
        el-link(@click="actionHandle(scope.id, 'view')" type="primary") 详情
        el-link(v-if="scope.payStatus !== 1" @click="notifyOrderHandle(scope)" type="primary") 通知
        <!--el-link(@click="printHandle(scope)" type="primary") 打印-->
        el-popconfirm(
          title="您确认要作废该账单吗?"
          @confirm="() => actionHandle(scope.id, 'invalid')"
          @onConfirm="() => actionHandle(scope.id, 'invalid')"
        )
          el-link(slot="reference" v-if="scope.payStatus !== 1" type="danger") 作废
      template(slot="created" slot-scope="text, scope")
        span {{text | dateFilter('YYYY/MM/DD')}}
      template(slot="payStatus" slot-scope="text, scope")
        el-tag(size="mini" :type="text | stautsFilter('type')") {{text | stautsFilter('name')}}
    router-view(v-else)
    info-drawer(:visible.sync="modalObj.visible" :id="modalObj.id" :type="modalObj.type")
</template>
<script>
import { cancelOrder, notifyOrder, notifyPlan, getFindorder } from './api'
import { accountColumn, payStatusList } from './config'
import InfoDrawer from './infoDrawer'
import { getClassesByArea } from '@/api/common'
import { mapGetters } from 'vuex'
export default {
  name: 'FinancePlan',
  components: {
    InfoDrawer
  },
  filters: {
    stautsFilter (val, key) {
      const status = payStatusList.find(x => x.id === val?.toString()) || {}
      return status[key] || ''
    }
  },
  data () {
    return {
      id: '',

      tableObj: {
        column: accountColumn
      },

      modalObj: {
        visible: false
      },
      classes: []
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    reqUrl () {
      return 'crm/fin/order/list'
    },
    searchField () {
      return [
        {
          key: 'classId',
          label: '班级名称',
          type: 'select',
          fieldProps: {
            options: this.classes,
            props: { value: 'id', label: 'name' }
          }
        },
        {
          key: 'payStatus',
          label: '缴费状态',
          type: 'select',
          fieldProps: {
            options: payStatusList,
            props: { value: 'id', label: 'name' }
          },
          initialValue: null
        },
        {
          key: 'childName',
          label: '学生姓名'
        }
      ]
    }
  },
  created () {
    this.id = this.$route.query.id
    this.getClasses()
  },
  methods: {
    refreshTable (flag = false) {
      this.$refs.table.refresh(flag)
    },

    actionHandle (id, type) {
      if (type === 'invalid') {
        cancelOrder({ id: id }, 'post').then(res => {
          this.$message.success('作废成功')
          this.refreshTable()
        })
      } else if (type === 'view') {
        this.modalObj = {
          visible: true,
          id: id,
          type: 'order'
        }
      }
    },

    notifyOrderHandle (row) {
      notifyOrder({ id: row.id }).then(res => {
        this.$message.success('发送成功')
      })
    },

    notifyPlanHandle () {
      notifyPlan({ planId: this.id }).then(res => {
        this.$message.success('发送成功')
      })
    },
    // 获取班级列表
    async getClasses () {
      const { curArea } = this
      this.classes = await (getClassesByArea({ areaId: curArea.areaId }) || [])
    },
    printHandle (item) {
      console.log(item)
      getFindorder({ id: item.id }).then(res => {
        console.log(res)
        this.printTwoFun(res)
      })
    },
    printTwoFun (item) {
      var win = window.open('')
      const totalUp = this.digit_uppercase(item.totalAmount)
      // 写入
      win.document.write(`
      <html>
          <head>
              <title>收费通知单</title>
          </head>
          <style>
              .print-box {
                width: 800px;
                font-size: 14px;
                color: #666;
                margin: 0 auto;
              }
              .print-box table {
                padding-top: 10px;
                border-spacing: 0;
              }
              .print-box table th,
              .print-box table td {
                border: 0.5px solid #f8f8f8;
                padding: 5px;
                text-align: center;
              }
              .text-center {
                text-align: center;
              }
              .pl-10 {
                padding-left: 10px;
              }
              .text-right {
                text-align: right !important;
              }
              .color-333 {
                color: #333;
              }
              .font-b {
                font-weight: bold;
              }
          </style>
          <body>
        <div id="detailePrintStyle">`)
      win.document.write(`
      <div class="print-box"" style=" padding:10px">
      <h3 class="text-center">` + item.title + `收费通知单</h3>
      <div>
        <span>编号：<span class="color-333">` + item.orderSn + `</span> </span>
        <span class="pl-10">学生：<span class="color-333">` + item.childName + `</span> </span>
        <span class="pl-10">班级：<span class="color-333">` + item.className + `</span> </span>
      </div>
      <table cellpadding="0">
        <tr>
          <th width='50'>序号</th>
          <th width='300'>项目/方案</th>
          <th width='100'>价格 </th>
          <th width='100'>数量 </th>
          <th width='100'>金额 </th>
          <th width='150'>说明</th>
        </tr>
        <tr>
          <td>1</td>
          <td>` + item.contract.name + `</td>
          <td>` + item.contract.practicalAmount + `</td>
          <td>` + item.contract.count + `</td>
          <td>` + item.contract.totalAmount + `</td>
          <td>` + item.remark + `</td>
        </tr>
        <tr>
          <td colspan='3'>合计：<span class="color-333 font-b">` + item.totalAmount + `</span> </td>
          <td colspan='3'>大写：<span class="color-333 font-b">` + totalUp + `</span></td>
        </tr>
        <tr>
          <td colspan='6' class='text-right'>备注：<span class="color-333">` + item.remark + `</span></td>
        </tr>
      </table>
      <p>制表人：<span class="color-333">` + item.createdByName + `</span> </p>
      <p>注脚：<span class="color-333">` + item.footnote + `</span> </p>
    </div>
      `)
      // var tableToPrintA = document.getElementById('BtableA')
      // win.document.write(tableToPrintA.outerHTML);
      win.document.write('</div></body></html>')
      win.document.close()// 在IE浏览器中使用必须添加这一句
      win.focus()// 在IE浏览器中使用必须添加这一句
      win.print()
      win.close()
    },
    digit_uppercase (n) {
      var digit = [
        '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'
      ]
      var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ]
      var s = ''
      for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = ''
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p
          n = Math.floor(n / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }
      return s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^$/, '零元') + '整'
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
